package com.sskj.extract;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.*;

public class Back {
    private static List<File> fileList = new LinkedList<>();

    private static Map<String, String> stringXmlMap = new HashMap<>();//string.xml中的别名与对应汉字

    private enum FileType {
        XML, JAVA, KT, OTHER
    }

    public static void main(String[] args) {
        back();
    }

    public static void back() {

        Map<String, String> map = Config.getMap();
        map.forEach((s, s2) -> {
            stringXmlMap.clear();
            fileList.clear();
            findAllXmlMap(s);
            findFile(s);
            replaceAll();
        });

    }

    private static void autoReplaceJava(File file, String find, String replace) {
        //记录文件长度
        Long fileLength = file.length();
        //记录读出来的文件的内容
        byte[] fileContext = new byte[fileLength.intValue()];
        FileInputStream in = null;
        PrintWriter out = null;
        String name = file.getName();
        if (name.contains(".")) {
            name = name.substring(0, name.indexOf("."));
        }
        try {
            in = new FileInputStream(file);
            //读出文件全部内容(内容和文件中的格式一致,含换行)
            in.read(fileContext);
            // 避免出现中文乱码
            String str = new String(fileContext, "utf-8");
            //修改对应字符串内容
            ArrayList<String> regex = new ArrayList<>();
            regex.add("App.INSTANCE.getString(R.string." + find + ")");
            regex.add("context.getString(R.string." + find + ")");
            regex.add("getResources().getString(R.string." + find + ")");
            regex.add("App.INSTANCE. getString(R.string." + find + ")");
            regex.add("activity.getString(R.string." + find + ")");
            regex.add("getString(R.string." + find + ")");
//            regex.add("R.string." + find );
            for (int i = 0; i < regex.size(); i++) {

                str = str.replace(regex.get(i), "\"" + replace + "\"");
            }
            //再把新的内容写入文件
            out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            out.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void autoReplaceXml(File file, String find, String replace) {
        //记录文件长度
        Long fileLength = file.length();
        //记录读出来的文件的内容
        byte[] fileContext = new byte[fileLength.intValue()];
        FileInputStream in = null;
        PrintWriter out = null;
        String name = file.getName();
        if (name.contains(".")) {
            name = name.substring(0, name.indexOf("."));
        }
        try {
            in = new FileInputStream(file);
            //读出文件全部内容(内容和文件中的格式一致,含换行)
            in.read(fileContext);
            // 避免出现中文乱码
            String str = new String(fileContext, "utf-8");
            //修改对应字符串内容
            String find1 = "\"@string/" + find + "\"";
            str = str.replace(find1, "\"" + replace + "\"");
//            String find1 = "@string/" + find ;
//            str = str.replace(find1, replace );
            //再把新的内容写入文件
            out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));

            out.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    private static void replaceAll() {
        stringXmlMap.forEach((s, s2) -> {
            fileList.forEach(file -> {
                readFile(file, s, s2);
            });
        });
    }

    public static void readFile(File file, String find, String replace) {
        switch (checkFile(file)) {
            case XML:
                autoReplaceXml(file, find, replace);
                break;
            case JAVA:
                autoReplaceJava(file, find, replace);
                break;
        }
    }

    public static FileType checkFile(File file) {
        String name = file.getName();
        String typeName = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        if (typeName.equals("xml")) {
            return FileType.XML;
        }
        if (typeName.equals("java")) {
            return FileType.JAVA;
        }
        if (typeName.equals("kt")) {
            return FileType.KT;
        }
        return FileType.OTHER;
    }

    private static void findAllXmlMap(String model) {
        String path = model + "/src/main/res/values/strings.xml";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document document = builder.parse(path);
//            //查找是否相同
            NodeList stringList = document.getElementsByTagName("string");
            for (int j = 0; j < stringList.getLength(); j++) {
                Node node = stringList.item(j);
                Element element = (Element) node;
                String name = element.getAttribute("name");
                String value = element.getTextContent();
                stringXmlMap.put(name, value);
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查找文件夹下的文件
     */
    public static void findFile(String path) {
        //文件夹
        File file = new File(path);
        if (file.exists()) {
            if (file.isDirectory()) {
                //文件夹下的文件
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    //遍历文件
                    for (File file1 : files) {
                        if (file1.isDirectory()) {
                            if (!file1.getAbsolutePath().contains("build")) {
                                findFile(file1.getAbsolutePath());
                            }
                        } else {
                            System.out.print(file1.getName() + "\n");
                            fileList.add(file1);
                        }
                    }
                }
            } else {
                System.out.print(file.getName() + "\n");
                fileList.add(file);
            }

        }

    }


}
